<template>
  <div class="create-order">
    <s-header :title="'生成订单'" ></s-header>
    <div class="address-wrap">
      <div class="name" v-show="addressList">
        <span>{{addressList[0].sname}}</span>&nbsp;
        <span>{{addressList[0].phone}}</span>
      </div>
      <div class="address" v-show="addressList">
        {{addressList[0].province}}&nbsp;
        {{addressList[0].city}}&nbsp;
        {{addressList[0].town}}&nbsp;&nbsp;
        {{addressList[0].detail_address}}
      </div>
      <van-icon class="arrow" name="arrow" @click="onEdit" />
    </div>
    <div class="good">
      <div class="good-item" v-for="i in cartData" :key="i.goods_id">
        <div class="good-img">
          <img :src="i.image" alt="" />
        </div>
        <div class="good-desc">
          <div class="good-title">
            <span>{{ i.goods_name }}</span>
            <span>x{{ i.goods_count }}</span>
          </div>
          <div class="good-btn">
            <div class="price">¥{{ i.price }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="pay-wrap">
      <div class="price" v-show="!show">
        <span>商品金额</span>
        <span>¥{{ total }}</span>
        <van-button
          class="pay-btn"
          type="primary"
          block
          is-link
          @click="showPopup"
          >生成订单</van-button
        >
      </div>
      <van-button class="pay-btn" type="primary" block is-link @click="showPopup">生成订单</van-button>
    </div>

    <van-popup 
      v-model:show="show" 
      closeable :close-on-click-overlay=false 
      position="bottom" 
      :style="{ height: '30%' }"
      @close="onClose"  
    >
      <div class="pay-choose">
        <van-button class="Alipay" block @click="Alipay">支付宝支付</van-button>
        <van-button class="Wechartpay" block @click="Wechartpay">微信支付</van-button>
      </div>
    </van-popup>

  </div>
</template>

<script setup lang="ts">
import sHeader from '@/components/SimpleHeader';
import { Toast } from 'vant';
import { ref,onMounted,computed} from 'vue';
import { useRouter,useRoute } from 'vue-router';
import {getAddress} from '@/service/address'
import {CreatOrder,payOrder} from '@/service/order'
import { login } from '@/service/user';

const router = useRouter()
const route = useRoute()
interface AddressData {
	id: number;
	createdAt: string;
	updatedAt: string;
	deletedAt?: any;
	sname: string;
	phone: string;
	province: string;
	city: string;
	town: string;
	username: string;
	detail_address: string;
	address_id: number;
	isdefault: number;
}

// 定义购物车数据类型
interface CartData {
  goods_id: string;
  count: number;
  goods_count: number;
  price: number;
  goods_name: string;
  image: string;
}

let addressList = ref<AddressData[]>([
  {
    id: 0,
	createdAt: "",
	updatedAt: "",
	deletedAt: "",
	sname: "",
	phone: "",
	province: "",
	city: "",
	town: "",
	username: "",
	detail_address: "",
	address_id: 0,
	isdefault: 0,
  }
])  
let cartData=ref<CartData[]>([])    
let show = ref(false)
let addressData
let orderId :number
const address = ref(route.query.ID)  //新选择的地址



// 计算总价
let total = computed(() => {
    let sum = 0
    cartData.value.forEach(item => {
      sum += item.goods_count * item.price
    })
    // @ts-ignore
    params.total_money = sum
    // @ts-ignore
    payParams.total_money = sum
    return sum
})

const params = {
  goods_ids:[],
  total_money:"",
  address_id:"",
  }
  const payParams = {
    order_id:0,
    pay_method:0,
    total_money:0,
  }

onMounted(() => {
  init();
});

// 初始化页面
async function init(){
  Toast.loading({ message: '加载中...', forbidClick: true });
  addressData= await getAddress(); // 地址数据
  // @ts-ignore
  cartData.value=JSON.parse(localStorage.getItem("cartItemIds"))  // 订单数据

  // @ts-ignore
  for(let item of cartData.value){
    // @ts-ignore
    params.goods_ids.push(String(item.goods_id))
  }
  // 获得默认地址
  const defaultAddress = addressData.data.filter((item: any) => {
    for (let i in item) {
      if (i == "isdefault" && item[i] == 1) return true;
    }
  })

  // 选择后得到的新地址
  
  if(defaultAddress[0]){
    console.log("有默认地址");
    if(address.value){//路由中有数据  即新确定的地址
      let newList = addressData.data.filter((item: any) => item.ID === Number(route.query.ID));
      addressList.value[0] = newList[0]
    }else{//路由中没有数据  定为默认地址
      addressList.value[0] = defaultAddress[0]
    }
    params.address_id = String(addressList.value[0].address_id)
  }else{
    console.log("没有默认地址");
    router.push(`address?`)}  
    Toast.clear()
}



async function showPopup() {
  show.value = true
  // @ts-ignore
  const orderData = await CreatOrder(params)
  orderId = orderData.data.order_id
  payParams.order_id  = orderId
  
}

// 点击关闭需要跳到我的订单页面--状态(待支付)
function onClose() {
  show.value = false
  router.push({path:`order?`})
}

// 支付宝支付--已支付--跳到我的订单页面
async function Alipay() {
  show.value = false;
  payParams.pay_method = 1
  // @ts-ignore
  await payOrder(payParams)
  router.push({path:`order?`})
}
// 微信支付--已支付--跳到我的订单页面
async function Wechartpay() {
  show.value = false;
  payParams.pay_method = 2
  // @ts-ignore
  await payOrder(payParams)
  router.push({path:`order?`})
}

// 生成订单
const onEdit = (item: AddressData, index: number): void => {
  router.push({
    path: `address?`,
  });
};
</script>

<style lang="less" scoped>
@import "../common/style/mixin";
.create-order {
  font-size: 14px;
  background: #f9f9f9;

  .address-wrap {
    margin-bottom: 20px;
    background: #fff;
    position: relative;
    margin-top: 44px;
    font-size: 14px;
    padding: 15px;
    color: #222333;
    text-align: left;
    .name,
    .address {
      margin: 10px 0;
      margin-right: 12px;
    }

    .arrow {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
    }

    &::before {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: -webkit-repeating-linear-gradient(
        135deg,
        #ff6c6c 0,
        #ff6c6c 20%,
        transparent 0,
        transparent 25%,
        #1989fa 0,
        #1989fa 45%,
        transparent 0,
        transparent 50%
      );
      background: repeating-linear-gradient(
        -45deg,
        #ff6c6c 0,
        #ff6c6c 20%,
        transparent 0,
        transparent 25%,
        #1989fa 0,
        #1989fa 45%,
        transparent 0,
        transparent 50%
      );
      background-size: 80px;
      content: "";
    }
  }

  .good {
    margin-bottom: 120px;
    height: 550px;
    overflow: scroll;
  }

  .good-item {
    padding: 10px;
    background: #fff;
    display: flex;

    .good-img {
      img {
        .wh(100px, 100px);
      }
    }

    .good-desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      padding: 20px;

      .good-title {
        display: flex;
        justify-content: space-between;
      }

      .good-btn {
        display: flex;
        justify-content: space-between;

        .price {
          font-size: 16px;
          color: red;
          line-height: 28px;
        }

        .van-icon-delete {
          font-size: 20px;
          margin-top: 4px;
        }
      }
    }
  }

  .pay-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    padding: 10px 0;
    padding-bottom: 50px;
    border-top: 1px solid #e9e9e9;

    > div {
      display: flex;
      justify-content: space-between;
      padding: 0 5%;
      margin: 10px 0;
      font-size: 14px;

      span:nth-child(2) {
        color: red;
        font-size: 18px;
      }
    }
    .pay-btn {
      position: fixed;
      bottom: 7px;
      right: 0;
      left: 0;
      width: 90%;
      margin: 0 auto;
    }

    .van-button {
      background: @primary;
    }
  }

  .pay-choose {
    width: 100%;
    position: absolute;
    background: #fff;
    bottom: 0;
    padding-top: 30px;
    padding-bottom: 30px;
    .Alipay {
      margin: 0 auto;
      width: 90%;
      color: rgb(255, 255, 255);
      background: rgb(25, 137, 250);
      border-color: rgb(25, 137, 250);
      margin-bottom: 10px;
    }
    .Wechartpay {
      margin: 0 auto;
      width: 90%;
      color: rgb(255, 255, 255);
      background: rgb(79, 192, 141);
      border-color: rgb(79, 192, 141);
    }
  }
}
</style>